package com.baizhi.lucene.demo1;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;

public class LuceneTest {
	/**
	 * 将数据添加到索引库
	 * 
	 * 
	 * @throws Exception
	 */
	@Test
	public void test1() throws Exception {
		// 0. 初始化索引配置:分析器+索引工具版本
		Analyzer an = new StandardAnalyzer(Version.LUCENE_4_9);
		IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_4_9, an);
		// 1. 指定索引位置
		Directory dir = FSDirectory.open(new File("D:/Index"));

		// 2. 创建索引工具
		IndexWriter iw = new IndexWriter(dir, iwc);
		// 3. 添加索引
		Document doc = new Document();// 一条数据的格式，相当于数据库中一条数据
		String str = "this is test elasticsearch code";
		doc.add(new Field("fname", str, TextField.TYPE_NOT_STORED));// 相当于字段。
		iw.addDocument(doc);
		// 4. 关闭连接，添加索引过程是加锁的，如果不关闭，将会导致其他程序无法写入，只有执行了close才会解锁。标识就是write.lock文件。
		iw.close();
		dir.close();
	}

	/**
	 * 根据关键词查询索引
	 * 
	 * @throws Exception
	 */
	@Test
	public void test2() throws Exception {
		// 1. 指定查询的索引库位置
		Directory dir = FSDirectory.open(new File("D:/Index"));
		DirectoryReader dr = DirectoryReader.open(dir);
		IndexSearcher reader = new IndexSearcher(dr);
		// 2. 创建索引查询工具 :指定条件字段
		Analyzer an = new StandardAnalyzer(Version.LUCENE_4_9);
		QueryParser qp = new QueryParser(Version.LUCENE_4_9, "fname", an);
		Query query = qp.parse("test");
		// 3. 执行查询
		TopDocs topDocs = reader.search(query, null, 1000);
		ScoreDoc[] docs = topDocs.scoreDocs;
		
		for (ScoreDoc doc : docs) {
			Document document = reader.doc(doc.doc);
			System.out.println(document.get("fname"));
		}
		
		// 5. 关闭流
		dr.close();
		dir.close();
	}

}
